package com.rms.hkpc.control;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;

public class EditTextDRClick extends AppCompatEditText {

    private Drawable drawable;
    private boolean isClick = true;

    public EditTextDRClick(@NonNull Context context) {
        super(context);
        init();
    }

    public EditTextDRClick(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public EditTextDRClick(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        drawable = getCompoundDrawables()[2];
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            this.setCompoundDrawables(null, null, drawable, null);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                boolean touchable = event.getRawX() >= (getRight() - drawable.getBounds().width());
                if (touchable) {
                    if (isClick) {
                        this.setInputType(128);
                        isClick = false;
                    } else {
                        this.setInputType(129);
                        isClick = true;
                    }
                    setSelection(getText().toString().length());
                }
            }
        }
        return super.onTouchEvent(event);
    }
}
